package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;



import java.io.IOException;
import java.util.ArrayList;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SmallVideosService {
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private FocusUserApi focusUserApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /*上传视频及图片*/
    @CacheEvict(value = "videoList",allEntries = true)
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //上传图片到阿里云,获得URL
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoFile.getInputStream());
        //上传视频到fast,获得URL
        String filename = videoFile.getOriginalFilename();  //ssss.avi
        String sufix = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), sufix, null);//文件输入流，文件长度，文件后缀，元数据
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //构建VIdio对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //..调用API保存视频
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    /*视频列表查询*/
    @Cacheable(
            value="videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")  //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {
/*        //1/首先查询Redis中的视频,存储结构<String,String>
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            if ((page - 1) * pagesize < values.length) {
                //获取所有视频的vids
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize)
                        .limit(pagesize).map(e -> Long.valueOf(e)).collect(Collectors.toList());
                list = videoApi.findMovementsByVids(vids);
                //5、调用API根据PID数组查询动态数据
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);

        }

        //4、如果redis数据不存在，分页查询mongdb视频数据
        if (list.isEmpty()) {
            list = videoApi.queryVideoList(page - redisPages, pagesize);
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                vos.add(vo);
            }

        }
        return new PageResult(page, pagesize, 0l, vos);*/

 //1、调用API查询 ： PageReulst<Video>
    PageResult pr=  videoApi.findAll(page,pagesize);
        //2、获取分页中的list集合  List<Video>
        List<Video> items= (List<Video>) pr.getItems();
        //3、循环视频列表，一个Video构造一个Vo
        List<VideoVo> vos=new ArrayList<>();
        for (Video item : items) {
            UserInfo userInfo = userInfoApi.findById(item.getUserId());
            VideoVo vo = VideoVo.init(userInfo, item);
            //从redis中获取，当前用户是否已经关注了视频发布作者
            String key = "focusUser_"+UserHolder.getUserId()+"_"+item.getUserId();
            if (redisTemplate.hasKey(key)) {
                vo.setHasFocus(1);
            }
            vos.add(vo);
        }
        //4、替换result中的item数据
        pr.setItems(vos);
        //5、构造返回值
        return pr;
    }
    /*关注*/
    public void userFocus(Long followUserId) {
        //1、创建FollowUser对象，并设置属性
        FocusUser followUser = new FocusUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        //2、调用API保存
        focusUserApi.saveFocusUser(followUser);
        //3、将关注记录存入redis中
        String key = Constants.FOCUS_USER + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key,hashKey,"1");

    }
    /*须取消关注*/
    public void userUnFocus(Long followUserId) {

        //1、调用API删除关注数据
        focusUserApi.deleteFocusUser(UserHolder.getUserId(),followUserId);
        //2、删除redis中关注记录
        String key = Constants.FOCUS_USER + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key,hashKey);
    }
}